CurPath = fileparts(mfilename('fullpath'));
load(fullfile(LFW.dbpath, 'ImgPairs.mat'), 'same_labels', 'diff_labels')

% load(fullfile(LFW.dbpath, 'FeaturePairs.mat'))
load(fullfile(LFW.dbpath, 'VGGFeaturePairs.mat'))

lfw_labels = [same_labels same_labels; diff_labels];
clear same_labels diff_labels

SampleNum = size(Features1, 2);

n_fold = 10;
n_num = 300;
svmcmd = '-t 0 -h 0';
HalfNum = SampleNum / 2;
same_label = [ones(HalfNum, 1); zeros(HalfNum, 1)];
accuracies = zeros(n_fold, 1);

F10 = Features1';
F10 = bsxfun(@rdivide, F10, sqrt(sum(F10.^2,2)));
F20 = Features2';
F20 = bsxfun(@rdivide, F20, sqrt(sum(F20.^2,2)));
clear Features1 Features2

for i = 1 : n_fold
    j0 = (i-1)*n_num;
    test_idx = [j0+1 : j0+n_num, j0+HalfNum+1 : j0+HalfNum+n_num];
    train_idx = 1 : SampleNum;
    train_idx(test_idx) = [];
    
    train = [F10(train_idx,:); F20(train_idx,:)];
    train_label = [lfw_labels(train_idx,1); lfw_labels(train_idx,2)];
    [normX, PCAmap] = compute_mapping(train, 'PCA', 310);
    [mappedX, mapping] = JointBayesian(normX, train_label);
    
    F1 = bsxfun(@minus, F10, PCAmap.mean) * PCAmap.M;
    F2 = bsxfun(@minus, F20, PCAmap.mean) * PCAmap.M;
    
%     thresh = zeros(size(train_idx,2),1);
%     for j = 1:size(train_idx,2)
%         thresh(j) = F1(train_idx(j),:) * mapping.A * F1(train_idx(j),:)' + F2(train_idx(j),:) * mapping.A * F2(train_idx(j),:)' - 2 * F1(train_idx(j),:) * mapping.G * F2(train_idx(j),:)';
%     end
    thresh = zeros(size(F1,1),1);
    for j = 1 : size(F1, 1)
        thresh(j) = F1(j,:) * mapping.A * F1(j,:)' + F2(j,:) * mapping.A * F2(j,:)' - 2 * F1(j,:) * mapping.G * F2(j,:)';
    end
    
    model = libsvm.svmtrain(same_label(train_idx),thresh(train_idx), svmcmd);
    % [class] = libsvm.svmpredict(same_label(train_idx),thresh(train_idx),model);
    [class, accuracy, deci] = libsvm.svmpredict(same_label(test_idx),thresh(test_idx),model);
    accuracies(i) = accuracy(1);
    fprintf('fold = %d/%d, accuracy = %.2f%%\n', i, n_fold, accuracies(i));
end

mu = mean(accuracies);
fprintf('mean accuracy = %.2f%%\n', mu);
